﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TheMethod
{
    public class LinearRegression
    {
        /// <summary>
        /// 构建线性回归模型
        /// </summary>
        /// <param name="gdp"></param>
        /// <param name="year"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public static double LinearRegressionModel(double[]gdp, double[]year, double x, double y)
        {
            //定义x,y的总和和平均值
            double avex = 0,avey = 0;
            double sumx = 0,sumy = 0;
            double a = 0,b = 0;
            //求x,y的总和
            for(int i = 0; i <gdp.Length; i++)
            {
                sumx += year[i];
                sumy += gdp[i];
            }
            //求x,y的平均值
            avex = sumx/gdp.Length;
            avey = sumy/gdp.Length;
            //定义分子分母
            double numerator = 0,denominator = 0;
            for(int j = 0; j <gdp.Length; j++)
            {
                numerator += (year[j] - avex) * (gdp[j] - avey);
                denominator += (year[j] - avex) * (year[j] - avex);
            }
            //求出方程中的常数和系数
            b = numerator/denominator;
            a = avey - b * avex;
            y = a + b * x;
            return y;
        }
    }
}
